package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.xxx.xbutler.common.RedisKeys;
import io.xxx.xbutler.config.TanJingProperties;
import io.xxx.xbutler.data.RobotMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.GenderType;
import io.xxx.xbutler.domain.HeartbeatStatus;
import io.xxx.xbutler.domain.Robot;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 分页获取商家机器人详情列表回调
 *
 * <pre>
 * {
 *     "Data": {
 *         "count": 0,
 *         "fails": [],
 *         "items": [
 *             {
 *                 "sex": 1,
 *                 "type": 30,
 *                 "whats_up": "志存高远",
 *                 "wx_alias": "dengbin19910916",
 *                 "nick_name": "邓斌",
 *                 "headimg_url": "https://wx.qlogo.cn/mmhead/ver_1/duL6P7rffIVRFfBVpF6OlfQHqeQiblgPeKCQ1Qsy91KLZNj6nC9rYY98JcWsa2KgYicwq0JJPzkn5UK0sQpYxaibwdwBfdjKmwD3FbKwBiajs59YX9R3PK1xnuUu8aODojoD/132",
 *                 "robot_wx_id": "wxid_arpszpwvw10n21",
 *                 "seal_status": 10,
 *                 "is_func_limit": false,
 *                 "chatroom_count": 259,
 *                 "person_qr_code": "",
 *                 "auto_add_friend": false,
 *                 "base64_whats_up": "5b+X5a2Y6auY6L+c",
 *                 "robot_serial_no": "14BC26C1F23A77A07760672146180AF5",
 *                 "base64_nick_name": "6YKT5paM",
 *                 "heartbeat_status": 20,
 *                 "auto_join_chatroom": false,
 *                 "open_chatroom_count": 0,
 *                 "is_allow_join_big_group": false,
 *                 "person_qr_code_encryption": ""
 *             }
 *         ],
 *         "max_id": 12183291
 *     },
 *     "nType": 1090,
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "nTimeStamp": 1737854940247,
 *     "vcSerialNo": "20250126092900188116414327330",
 *     "vcRobotWxId": "",
 *     "vcMerchantNo": "202407150008480",
 *     "vcRobotSerialNo": ""
 * }
 * </pre>
 */
@Slf4j
@Component
public class _1090Handler implements CallbackHandler {

    @Resource
    private TanJingProperties properties;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RobotMapper robotMapper;

    @Override
    public String name() {
        return "分页获取商家机器人详情列表回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 1090;
    }

    @Override
    public void handle(Callback callback) {
        JSONObject data = (JSONObject) callback.getData();
        RBucket<Long> queryRobotsMaxId = redissonClient.getBucket(RedisKeys.queryRobotsMaxId(properties.getMerchant().getId()));
        queryRobotsMaxId.set(data.getLong("max_id"));

        LocalDateTime now = LocalDateTime.now();
        for (JSONObject info : data.getList("items", JSONObject.class)) {
            Robot robot = (Robot) new Robot()
                    .setPlatformType(info.getInteger("type"))
                    .setSealStatus(info.getInteger("seal_status"))
                    .setQrcode(info.getString("person_qr_code"))
                    .setAllowJoinBigRoom(info.getBoolean("is_allow_join_big_group"))
                    .setFunctionLimited(info.getBoolean("is_func_limit"))
                    .setHeartbeatStatus(HeartbeatStatus.valueOf(info.getIntValue("heartbeat_status")))
                    .setAutoAddFriend(info.getBoolean("auto_add_friend"))
                    .setAutoJoinRoom(info.getBoolean("auto_join_chatroom"))
                    .setRoomCount(info.getInteger("chatroom_count"))
                    .setOpenRoomCount(info.getInteger("open_chatroom_count"))
                    .setId(info.getString("robot_wx_id"))
                    .setName(info.getString("nick_name"))
                    .setBase64Name(info.getString("base64_nick_name"))
                    .setAvatar(info.getString("headimg_url"))
                    .setAlias(info.getString("wx_alias"))
                    .setGender(GenderType.valueOf(info.getInteger("sex")))
                    .setWhatsUp(info.getString("whats_up"))
                    .setBase64WhatsUp(info.getString("base64_whats_up"))
                    .setUpdatedTime(now);


            boolean exists = isExists(robot);
            if (exists) {
                robot.setUpdatedTime(now);
                robotMapper.updateById(robot);
            } else {
                robotMapper.insert(robot);
            }
        }
    }

    private boolean isExists(Robot robot) {
        LambdaQueryWrapper<Robot> wrapper = new LambdaQueryWrapper<Robot>()
                .eq(Robot::getId, robot.getId());
        return robotMapper.exists(wrapper);
    }
}
